package org.nfIt.h5user.service.impl;

import org.nfIt.common.exception.CustomException;
import org.nfIt.dto.h5.UserRegisterDto;
import org.nfIt.entity.user.UserInfo;
import org.nfIt.h5user.mapper.UserInfoMapper;
import org.nfIt.h5user.service.UserInfoService;
import org.nfIt.utils.AuthContextUtil;
import org.nfIt.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * ClossName:UserInfoServiceImpl
 * Pakage:org.nfIt.h5user.service.impl
 * Description
 *
 * @Author L
 * @Create 2024/10/7 19:50
 * @Version 2023.1.3
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * h5前端用户注册
     * @param userRegisterDto 封装数据
     */
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //1 userRegisterDto获取数据
        //用户名
        String username = userRegisterDto.getUsername();
        //密码
        String password = userRegisterDto.getPassword();
        //昵称
        String nickName = userRegisterDto.getNickName();
        //验证码
        String code = userRegisterDto.getCode();


        //2 验证码校验
        //2.1 从redis获取发送验证码,前端是把username(用户名) 当作手机号
        String redisCode = redisTemplate.opsForValue().get(username);
        //2.2 获取输入的验证码，进行比对
        if (!redisCode.equals(code)) {
            throw new CustomException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //3 校验用户名不能重复
        UserInfo checkUserInfo = userInfoMapper.selectByUserName(username);
        if (checkUserInfo != null) {
            throw new CustomException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //4 封装添加数据，调用方法添加数据库
        //保存用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.save(userInfo);

        //删除发送的验证码，为什么呢？因为验证码用于注册，注册完成需要删除
        // 删除Redis中的数据
        Boolean delete = redisTemplate.delete(username);
        System.out.println("删除Redis中的数据"+delete);





    }
}
